<?php
class  Client_model extends CI_Model
{
        function __construct()
        {
                parent::__construct();
        }


        function get_category()
        {//Get the category
                $sql="select `classify_id`,`type` from `classify` where `tree`=1 order by classify_id asc";
                $query=$this->db->query($sql);
                if($query->num_rows()>0)
                        {
                        foreach($query->result() as $cate)
                        {
                                $cate_id=$cate->classify_id;
                                $bc=$cate->type;
                                $sql="select * from `classify` where `fid`=$cate_id order by `classify_id`";
                                $query=$this->db->query($sql);
                                if($query->num_rows>0)
                                {
                                        foreach ($query->result_array() as $val)
                                        {
                                                $se_cate[]=array('cate_id'=>$val['classify_id'],'bc'=>$val['type']);
                                        }
                                        //bc  book  category
                                        $category[]=array('cate_id'=>$cate_id,'bc'=>$bc,'se_cate'=>$se_cate);
                                        $se_cate='';
                                        //unset($se_cate);//上面的方法也可以
                                }
                                else
                                {
                                        $category[]=array('cate_id'=>$cate_id,'bc'=>$bc);
                                }
                        }
                        return $category;
                }
                else
                {
                        return false;//no category records
                }
        }

        function get_books_num()
        {
                $sql="select `b_id` from `books`";
                $query=$this->db->query($sql);
                $b_num=$query->num_rows;
                return $b_num;
        }
        function show_books($page)
        {
                $num=1024;
                $offset=($page-1)*$num;
                $sql="select `prod_id`,`name`,`author`,`publisher`,`price`,`pic`,`pub_date`,`star` from `books` limit $offset,$num";
                $query=$this->db->query($sql);
                if($query->num_rows>0)
                {
                        foreach($query->result() as $list)
                                {//change the key
                            $books[]=array('pid'=>$list->prod_id,'bn'=>$list->name,'au'=>$list->author,'pn'=>$list->publisher,'pc'=>$list->price,'bip'=>base_url().$list->pic,'pd'=>$list->pub_date,'star'=>$list->star);
                        }
                        return $books;
                        //return $books=array('record'=>0);
                }
                else
                {
                        return $books=array('record'=>0);
                }
        }


        function get_second_category($fid) {
                $se_cate=array();
                $sql="select * from `classify` where `fid`=$fid order by `classify_id`";
                log_message("debug", $sql);
                $query=$this->db->query($sql);
                if($query->num_rows>0) {
                        foreach ($query->result_array() as $val) {
                                log_message("debug", $val['classify_id']." ".$val['type']);
                                $se_cate[]=array('cate_id'=>$val['classify_id'],'bc'=>$val['type']);
                        }
                }

                return $se_cate;
        }

        function get_category_pic($fid,$type) {
                $pic="/CatPic/default.jpg";
                if ($type) {
                        $pic="/CatPic/".$type."/default.jpg";
                }

                $sql="select `pic` from `classify` where `classify_id`=$fid";
                $query=$this->db->query($sql);
                if ($query->num_rows > 0) {
                        $result = $query->row_array();
                        if ($type) {
                                $pic = "/CatPic/".$type."/".$result['pic'];
                        } else {
                                $pic = "/CatPic/".$result['pic'];
                        }
                }
                return base_url().$pic;
        }

        function every_category_nums($cate_id)
        {
                if($cate_id!='')
                {
						// isgore all books that is recommanded which means star = 5 
                        $sql="select s.b_id from slave s join books b on s.b_id=b.b_id where s.type_id='$cate_id' and b.sid<=0 and b.star<>5";
                        $query=$this->db->query($sql);
                        $every_category_nums=$query->num_rows();
                    return $every_category_nums;
                }
        }
        function every_category_list($cate_id,$page=1)
        {
                $num=1024;//every page  2 records
                $tatal_nums=$this->every_category_nums($cate_id);
                if($tatal_nums>0)
                {
                        $pageall=ceil($tatal_nums/$num);
                        if($page<1)
                        {
                                $page=1;
                        }
                        else
                        {
                                if($page>$pageall)
                                {
                                        $page=$pageall;
                                }
                        }
                                $offset=($page-1)*$num;
                                $sql="select b.prod_id,b.name,b.author,b.publisher,b.price,b.pic,b.pub_date,b.star,b.sid from books b  join slave s on b.b_id=s.b_id where s.type_id='$cate_id' and b.sid<=0 and b.star<>5 order by b.b_id DESC limit $offset,$num";
                                $query=$this->db->query($sql);
                            foreach($query->result() as $list)
                            {//change the key
                                    $pm[]=array('pid'=>$list->prod_id,'bn'=>$list->name,'au'=>$list->author,
                                                'pn'=>$list->publisher,'pc'=>$list->price,'bip'=>base_url().$list->pic,
                                                'pd'=>$list->pub_date,'star'=>$list->star, 'sid'=>$list->sid);
                            }
                            return $pm;
                }
                else
                {
                        return false;
                }
        }

        // we use star flag as popular flag, we just consider 5 as popular,and any other level(1-4) is not popular
        function every_popular_category_nums($cate_id)
        {
                if($cate_id!='')
                {
                        $sql="select s.b_id from slave s join books b on s.b_id=b.b_id where s.type_id='$cate_id' and b.sid<=0 and b.star=5";
                        $query=$this->db->query($sql);
                        $every_category_nums=$query->num_rows();
                    return $every_category_nums;
                }
        }
        function every_popular_category_list($cate_id,$page=1)
        {
                $num=1024;//every page  2 records
                $tatal_nums=$this->every_popular_category_nums($cate_id);
                if($tatal_nums>0)
                {
                        $pageall=ceil($tatal_nums/$num);
                        if($page<1)
                        {
                                $page=1;
                        }
                        else
                        {
                                if($page>$pageall)
                                {
                                        $page=$pageall;
                                }
                        }
                                $offset=($page-1)*$num;
                                $sql="select b.prod_id,b.name,b.author,b.publisher,b.price,b.pic,b.pub_date,b.star,b.sid from books b  join slave s on b.b_id=s.b_id where s.type_id='$cate_id' and b.sid<=0 and b.star=5 order by b.b_id DESC limit $offset,$num";
                                $query=$this->db->query($sql);
                            foreach($query->result() as $list)
                            {//change the key
                                    $pm[]=array('pid'=>$list->prod_id,'bn'=>$list->name,'au'=>$list->author,
                                                'pn'=>$list->publisher,'pc'=>$list->price,'bip'=>base_url().$list->pic,
                                                'pd'=>$list->pub_date,'star'=>$list->star, 'sid'=>$list->sid);
                            }
                            return $pm;
                }
                else
                {
                        return false;
                }
        }


        function get_book_message($prod_id)
        {
                $sql="select * from `books` where `prod_id`='$prod_id'";
                $query=$this->db->query($sql);
                if($query->num_rows()>0)
                {
                $msg=$query->row_array();
                $bid=$msg['b_id'];
                $sql2="select c.type from `slave` s join `classify` c on s.type_id=c.classify_id where s.b_id='$bid'";
                $cate=$this->db->query($sql2);
                $cate_name=$cate->row_array();
                $cate=$cate_name['type'];
                $message=array('pid'=>$msg['prod_id'],'isbn'=>$msg['isbn'],'bn'=>$msg['name'],'au'=>$msg['author'],'pn'=>$msg['publisher'],'pc'=>$msg['price'],'cp'=>base_url().$msg['dir_path'],'bd'=>$msg['describe'],'bip'=>base_url().$msg['pic'],'pd'=>$msg['pub_date'],'star'=>$msg['star'],'cate_name'=>$cate);
                if ($msg['sid'] == 0) {
                        $bid=$msg['b_id'];
                        $sql3="select * from `books` where `sid`=$bid";
                        $query3=$this->db->query($sql3);
                        foreach($query3->result() as $list) {
                                $message['sub_books'][] = array('pid'=>$list->prod_id,'isbn'=>$list->isbn,'bn'=>$list->name,'au'=>$list->author,'pn'=>$list->publisher,'pc'=>$list->price,'cp'=>base_url().$list->dir_path,'bd'=>$list->describe,'bip'=>base_url().$list->pic,'pd'=>$list->pub_date,'star'=>$list->star,'cate_name'=>$cate);
                        }
                }
                return $message;
                }
        }
        function purchase()
        {
                $ip=$this->input->post('ip');
                $pid=$this->input->post('pid');
                $ts=$_POST['ts'];
                $bs=base64_encode($ts);
                                /*
                $referer='https://sandbox.itunes.apple.com/verifyReceipt';
                //$referer='https://buy.itunes.apple.com/verfyReceipt';

                $result_data=array('receipt-data'=>$bs);
                $post_data=json_encode($result_data);
                //return  $post_data;

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_URL,$referer);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                $result = curl_exec($ch);
                if($result==NULL){
                    echo"Error:<br>";
                    echo curl_errno($ch)."-".curl_error($ch)."<br>";
                }
                curl_close($ch);
                //return $result;

                log_message("debug", "purchase result:".$result);
                $de_result=json_decode($result);//array
                                */
                //test code, for verify in apple failed
                $de_result->status=0;
                if($de_result->status==0)
                {
                        $sql="insert into `purchase` values('0','$ip','$pid','$ts')";
                        $this->db->query($sql);
                        $sql2="select `sid`,`b_id`,`dir_path`,`b_path` from `books` where `prod_id`='$pid'";
                        $result=$this->db->query($sql2);
                        $book_path=$result->row_array();
                        //$bid=$book_path['b_id'];
                        //$sql3="select c.type from `slave` s join `classify` c on s.type_id=c.classify_id where s.b_id='$bid'";
                        //$cate=$this->db->query($sql3);
                        //$cate_name=$cate->row_array();
                        //$cate=$cate_name['type'];
                        if ($book_path['sid'] == -1) {
                                $bp=array('status'=>0, 'type'=>-1, 'cp'=>base_url().$book_path['dir_path'],'bp'=>base_url().$book_path['b_path']);
                                return $bp;
                        } else if($book_path['sid'] == 0) {
                                $bp=array('status'=>0, 'type'=>0, 'sub_books'=>array());
                                $sid=$book_path['b_id'];
                                $sql3="select `sid`,`b_id`,`dir_path`,`b_path` from `books` where `sid`='$sid'";
                                $result=$this->db->query($sql3);
                                foreach ($result->result() as $list) {
                                        $bp['sub_books'][]=array('cp'=>base_url().$list->dir_path,'bp'=>base_url().$list->b_path);
                                }
                                return $bp;
                        }
                }
                else
                {
                        $bp=array('status'=>1);
                        return $bp;
                }
        }
        function search()
        {
                //$postdata = file_get_contents("php://input");
                //$data=json_decode($postdata);
                $sk=$this->input->post('sk');
                $page=$this->input->post('page');
                if ($page==0) $page=1;
                $sql="select `prod_id` from `books` where `name` like '%$sk%' or `author` like '%$sk%'; ";
                $query=$this->db->query($sql);
                $total_nums=$query->num_rows();
                if($total_nums>0)
                {
                        $pm = array();
                        $num=1024;//every page  2 records
                        $offset=($page-1)*$num;
                        $sql="select `prod_id`,`name`,`author`,`publisher`,`price`,`pic`,`pub_date`,`star`,`sid`, `b_id` from `books` where `name` like '%$sk%' or `author` like '%$sk%' order by `b_id` desc limit $offset,$num";
                        $query=$this->db->query($sql);
                        foreach($query->result() as $list)
                        {//change the key
								# filter the same result
								$hit = false;
								foreach ($pm as $p) {
									if ($p['bid'] == $list->b_id) {
										$hit=true;
										break;
									}
								}
								if ($hit == true) {
									$total_nums--;
									continue;
								}
								
                                # search the sub book
                                if ($list->sid > 0 ) {
                                        # only get the parent book once
                                        $hit = false;
                                        foreach ($pm as $p) {
                                                if($p['bid'] == $list->sid) {
                                                        $hit = true;
														$total_nums--;
                                                        break;
                                                }
                                        }
                                        # get the parent book
                                        if ($hit == false) {
                                                $sql2 = "select `b_id`,`prod_id`,`name`,`author`,`publisher`,`price`,`pic`,`pub_date`,`star`,`sid` from `books` where b_id = " . $list->sid;
                                                $query2=$this->db->query($sql2);
                                                if ($query2->num_rows() > 0) {
                                                        $result=$query2->row_array();
                                                        $pm[] = array('bid'=>$result['b_id'], 'pid'=>$result['prod_id'],'bn'=>$result['name'], 'au'=>$result['author'], 'pn'=>$result['publisher'], 'pc'=>$result['price'],
                                                                      'bip'=>base_url().$result['pic'], 'pd'=>$result['pub_date'], 'star'=>$result['star'], 'is_parent'=>1);
                                                } else {
													# in case of some leak sub books
													$total_nums--;
												}
                                        }
                                } else {
                                        $pm[]=array('bid'=>$list->b_id,'pid'=>$list->prod_id,'bn'=>$list->name,'au'=>$list->author,'pn'=>$list->publisher,'pc'=>$list->price,'bip'=>base_url().$list->pic,'pd'=>$list->pub_date,'star'=>$list->star);
                                }
                        }
						$result_all['b_num']=$total_nums;
                        $result_all['b_list']=$pm;
                        return $result_all;
                } else {
                        $result_all['b_num']=0;
                        return  $result_all;
                }
        }

        function get_comments_nums($pid)
        {

                $sql="select `evaluate_id` from `evaluate` where `prod_id`='$pid'";
                $query=$this->db->query($sql);
                return $query->num_rows();
        }
        function get_comments_list($pid,$page=1)
        {
                $num=1024;//every page  2 records
                $records=$this->get_comments_nums($pid);
                if($records>0)
                {
                        $offset=($page-1)*$num;
                        $sql="select `level`,`comment`,`date` from `evaluate` where `prod_id`='$pid' order by `evaluate_id` desc limit $offset,$num";
                        $query=$this->db->query($sql);
                        foreach($query->result() as $list)
                        {
                                $com[]=array('cl'=>$list->level,'bco'=>$list->comment,'cd'=>$list->date);
                        }
                        return $com;
                }
        }
        function insert_comments()
        {
            //$postdata = file_get_contents("php://input");
                //$data=json_decode($postdata);
                $pid=$this->input->post('pid');
                $cl=$this->input->post('cl');
                $bco=$this->input->post('bco');
                $sql="insert into `evaluate` values ('0','$pid','$cl','$bco',now())";
                if($this->db->query($sql))
                {
                        return (array('cs'=>0));
                }
                else
                {
                        return (array('cs'=>1));
                }
        }

}












































